package com.example.handler;

import com.example.model.R;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Set;
import java.util.stream.Collectors;

/**
 * @CreateTime 2025-03-08
 * @Description 全局异常
 */

@ControllerAdvice
public class GlobalExceptionHandler {

    // 处理参数校验异常
    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseBody
    public R handleConstraintViolation(ConstraintViolationException ex) {
        Set<ConstraintViolation<?>> violations = ex.getConstraintViolations();
        // 拼接所有错误信息
        String message = violations.stream()
                .map(v -> v.getMessage())
                .collect(Collectors.joining("; "));
        return R.fail("请求参数不合法: " + message);
    }

    // 处理请求体解析失败（如Body为空）
    @ExceptionHandler(HttpMessageNotReadableException.class)
    @ResponseBody
    public R handleHttpMessageNotReadable(HttpMessageNotReadableException ex) {
        return R.fail("请求体不能为空");
    }
}
